<template>
  <el-dialog
    :modelValue="visible"
    @update:modelValue="$emit('update:visible', $event)"
    class="report_dialog"
    width="70%"
  >
    <div class="title">增加规则</div>
    <div class="report_content">
      <div class="left_content">
        <el-input v-model.trim="iptvalue" placeholder="请输入规则" @input="searchFun">
          <template #prepend>
            <el-button :icon="Search" />
          </template>
        </el-input>
        <div class="bottom_left">
          <div class="left_one">
            <div
              class="left_one_item"
              v-for="(item, index) in sectionList"
              :class="{ active: sectionId === item.stationId }"
              :key="item.id"
              @click="sectionChange(item)"
            >
              {{ item.stationName }}
            </div>
          </div>
          <div class="left_two" @scroll="handleScroll" ref="scrollContainer">
            <el-checkbox
              v-for="(item, index) in ruleListAll"
              v-model="item.checked"
              :checked="checkedRuleList.findIndex((item1) => item1.ruleId === item.ruleId) !== -1"
              size="large"
              :key="item.ruleId"
              @change="
                (flag) => {
                  checkChange(item, flag)
                }
              "
            >
              <!-- <el-popover
                placement="top-start"
                title="Title"
                :width="200"
                trigger="hover"
                :content="item.station + ' ' + '/' + ' ' + item.title"
              >
                <template #reference>
                </template>
              </el-popover> -->
              {{ item.station + ' ' + '/' + ' ' + item.title }}
            </el-checkbox>
          </div>
          <!-- @change="checkedRuleList = ruleListAll.filter((item1) => item1.checked)" -->
        </div>
      </div>
      <div class="right_content">
        <div class="right_content_item" v-for="(item, index) in checkedRuleList" :key="index">
          <div class="right_item_title">{{ item.station }}&nbsp; / &nbsp;{{ item.title }}</div>
          <span @click="remove(item, index)">✕</span>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { onBeforeMount, onMounted, reactive, ref, toRaw } from 'vue'
import { useAuthStore } from '@/stores/auth.js'
import { Search } from '@element-plus/icons-vue'
import _ from 'lodash'
import { ElMessage, useDisabled } from 'element-plus'
import { getRuleCollectAPI, getStationAPI } from '@/api/ruleKind.js'
const emit = defineEmits(['update:visible', 'changeData'])
const authStore = useAuthStore()
const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
  },
})
const queryParams = reactive({
  pageSize: 20,
  page: 1,
})
const iptvalue = ref('')
const total = ref(0)
const sectionList = ref([])
const ruleListAll = ref([])
const scrollContainer = ref(null)
const checkedRuleList = ref([])
const sectionId = ref('')
const { proxy } = getCurrentInstance()
const state = reactive({})

const sectionChange = (data) => {
  sectionList.value
    .filter((item) => item.stationId !== data.stationId)
    .forEach((item) => {
      item.checked = false
    })
  if (data.checked) {
    queryParams.page = 1
    queryParams.station = null
    sectionId.value = null
    data.checked = false
    getList()
  } else {
    queryParams.page = 1
    queryParams.station = data.stationName
    sectionId.value = data.stationId
    data.checked = true
    getList()
  }
}

const handleScroll = _.debounce(() => {
  const container = scrollContainer.value
  const { scrollTop, clientHeight, scrollHeight } = container
  // 判断滚动条是否触底
  if (scrollTop + clientHeight >= scrollHeight - 1) {
    console.log('滚动条已触底')
    queryParams.page++
    if (total.value <= ruleListAll.value.length) return
    getRuleCollectAPI(queryParams).then((res) => {
      ruleListAll.value = [...ruleListAll.value, ...res.data.items]
      total.value = res.data.total
    })
    // 可以在这里添加触底后的逻辑，如加载更多数据等
  } else {
    console.log('滚动条未触底')
  }
}, 300)
const searchFun = _.debounce(() => {
  queryParams.page = 1
  queryParams.pageSize = 20
  queryParams.keywords = iptvalue.value
  getList()
}, 300)

const remove = (item, index) => {
  checkedRuleList.value.splice(index, 1)
  if (ruleListAll.value.find((item1) => item1.ruleId === item.ruleId)) {
    ruleListAll.value.find((item1) => item1.ruleId === item.ruleId).checked = false
  }
}
const checkChange = (data, flag) => {
  if (flag) {
    checkedRuleList.value.push(data)
  } else {
    checkedRuleList.value = checkedRuleList.value.filter((item) => item.ruleId !== data.ruleId)
  }
  console.log('data', data)
}
const handleClose = () => {
  emit('update:visible', false)
}
// watch(
//   () => {
//     return queryParams
//   },
//   (newValue) => {
//     getList()
//   },
//   {
//     deep: true,
//   },
// )
/** 提交按钮 */
function submitForm() {
  let submitData = _.cloneDeep(toRaw(checkedRuleList.value))
  if (submitData.length == 0) return ElMessage.warning('请选择规则')
  submitData.forEach((item) => {
    item.ruleContent.forEach((item1) => {
      item1.station = item.station
      item1.ruleId = item.ruleId + ''
    })
  })
  emit('changeData', submitData)
  emit('update:visible', false)
}
const getList = () => {
  getRuleCollectAPI(queryParams).then((res) => {
    ruleListAll.value = res.data.items
    total.value = res.data.total
  })
}
onBeforeMount(() => {})
onMounted(() => {
  getList()
  getStationAPI().then((res) => {
    if (res.code === 200) {
      sectionList.value = res.data
      // if (res.data && res.data.length > 0) {
      //   sectionId.value = res.data[0].stationId
      //   queryParams.station = res.data[0].stationName
      // }
    }
  })
})
defineExpose({ state })
</script>
<style lang="scss" scoped>
.report_dialog {
  .title {
    text-align: center;
    font-weight: 800;
    font-size: 18px;
    margin-bottom: 20px;
  }
  .report_content {
    display: flex;
    height: 600px;
    gap: 15px;
    .left_content {
      flex: 2;
      border: 1px solid #ccc;
      border-radius: 10px;
      padding: 15px;
      .bottom_left {
        display: flex;
        margin-top: 15px;
        height: 94%;
        .left_one {
          flex: 1;
          overflow-y: auto;
          border-right: 1px solid #ccc;
          .left_one_item {
            text-align: center;
            font-size: 17px;
            padding: 9px 0;
            cursor: pointer;
            &.active {
              color: rgba(67, 111, 246, 1);
              background-color: rgba(67, 111, 246, 0.1);
            }
          }
        }
        .left_two {
          flex: 2;
          padding: 0px 10px;
          overflow-y: auto;
          :deep(.el-checkbox) {
            display: block;
          }
          :deep(.el-checkbox__label) {
            margin-bottom: 5px;
            width: 205px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            vertical-align: middle;
            word-wrap: break-word;
          }
        }
      }
    }
    .right_content {
      border: 1px solid #ccc;
      border-radius: 10px;
      flex: 1;
      padding: 15px 15px 0px 15px;
      overflow-y: auto;
      .right_content_item {
        padding: 15px;
        border-radius: 15px;
        margin-bottom: 15px;
        border: 1px solid #ccc;
        position: relative;
        .right_item_title {
          font-size: 15px;
        }
        span {
          position: absolute;
          right: 0;
          top: -4px;
          width: 16px;
          text-align: center;
          height: 16px;
          line-height: 16px;
          background: red;
          color: #fff;
          border-radius: 50%;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
